import { Input, View } from '@tarojs/components';
import { Arrow } from '@taroify/icons';
import { InputListProps } from '@/types/props';
import {
  Button,
  Cell,
  Picker,
  Popup,
  Textarea,
  TextEllipsis,
  Image,
} from '@taroify/core';
import { useState } from 'react';
import { imgAddPrefix, isValidEmail, isValidPhone, toast } from '@/utils';
import { sendEamilCodeApi } from '@/api';
import MyInput from '../common/MyInput';

export default ({
  options,
  groupName,
  bordered = false,
}: {
  options: Array<InputListProps>;
  groupName?: string;
  bordered?: boolean;
}) => {
  const [open, setOpen] = useState(false);
  const [fn, setFn] = useState<InputListProps['setValue']>();
  const [cur, setCur] = useState('');
  const [max, setMax] = useState(100);
  const [verify, setVerify] = useState<InputListProps['verify']>();
  const [errMsg, setErrMsg] = useState('');
  const [popup, setPopup] = useState<InputListProps['popup']>();
  const [columns, setColumns] = useState<InputListProps['columns']>();
  const [code, setCode] = useState('');
  const [defaultValue, setDefaultValue] =
    useState<InputListProps['defaultValue']>();
  async function getCode(): Promise<boolean> {
    if (!cur) return false;
    if (popup == 'phone' && !isValidPhone(cur)) {
      toast('请输入正确的手机号');
      return false;
    } else if (popup == 'email' && !isValidEmail(cur)) {
      toast('请输入正确的邮箱地址');
      return false;
    }
    try {
      const res = await sendEamilCodeApi(cur);
      console.log(res);
      // 处理返回结果
      return true;
    } catch (title) {
      //   Taro.showToast({ title, icon: "none" });
      return false;
    }
  }
  function render() {
    if (popup == 'input')
      return (
        <View className="w-full px-4 py-2 box-border">
          <Textarea
            onInput={e => setCur(e.detail.value)}
            value={cur}
            className=" bg-gray-200 w-full p-3 box-border"
            style={{ minHeight: '80px' }} // 设置高度
            autoFocus
            autoHeight
            maxlength={max}
          />
          <View className="flex justify-end text-xs text-gray-400  gap-2 mt-5 items-center">
            <View>{max - cur.length}</View>
            <Button
              onClick={() => {
                if (verify && !verify(cur)) {
                  toast(errMsg);
                  return;
                }
                fn && fn(cur);
                setOpen(false);
              }}
              className="w-16"
              size="mini"
              color="primary"
              shape="round"
            >
              确定
            </Button>
          </View>
        </View>
      );
    else if (popup == 'picker')
      return (
        <Picker
          defaultValue={defaultValue}
          onCancel={() => setOpen(false)}
          title="标题"
          columns={columns}
          onConfirm={value => {
            fn && fn(value);
            setOpen(false);
          }}
        />
      );
    else if (popup == 'email' || popup == 'phone')
      return (
        <View className="flex px-4 mb-8 justify-center flex-col gap-4 items-center">
          <View className="">
            <Image
              className="h-20"
              mode="widthFix"
              src={imgAddPrefix(
                '/statics/assets/imgs/security.png',
                'http://127.0.0.1:9999',
              )}
            />
          </View>
          <View>为了您的账号安全，需要验证你的设备</View>
          <MyInput
            change={setCur}
            placeholder={`请输入原${
              popup == 'email' ? '邮箱地址' : '手机号码'
            }`}
          />
          <MyInput
            change={setCur}
            placeholder={`请输入新的${
              popup == 'email' ? '邮箱地址' : '手机号码'
            }`}
          />
          <MyInput change={setCode} getCode={getCode} type="code" />
          <Button color="primary" className="w-full">
            更换
          </Button>
        </View>
      );
  }
  function onClick(opt: InputListProps) {
    if (!opt.edit && !opt.rightHandler) {
      opt.setValue && setFn(() => opt.setValue);
      opt.verify && setVerify(() => opt.verify);
      opt.columns && setColumns(opt.columns);
      setErrMsg(opt.errMsg ?? '验证失败');
      setPopup(opt.popup ?? 'input');
      setOpen(true);
      typeof opt.value == 'string' &&
        (popup == 'input' || popup == 'picker') &&
        setCur(opt.value ?? '');
      setMax(opt.maxValue ?? 100);
      setDefaultValue(opt.defaultValue);
    } else if (opt.rightHandler) opt.rightHandler();
  }

  return (
    <View>
      <Cell.Group title={groupName} bordered={bordered}>
        {options.map((opt, i) => {
          return (
            <Cell
              align={opt.align ?? 'center'}
              key={i}
              onClick={() => onClick(opt)}
              title={opt.label}
              isLink={!opt.edit}
            >
              <View className="flex  items-center justify-end">
                {opt.ellipsis ? (
                  <TextEllipsis
                    content={typeof opt.value == 'string' ? opt.value : ''}
                    expandText="展开"
                    collapseText="收起"
                  />
                ) : (
                  <>{opt.value}</>
                )}
              </View>
            </Cell>
          );
        })}
      </Cell.Group>

      <Popup open={open} onClose={setOpen} placement="bottom">
        {render()}
      </Popup>
    </View>
  );
};
